<template>
  <div class="app-container">
        <div class="flex box">
      <div class="flex-l">
        <div class="titles">
          <img class="titles-left-img" src="@/assets/img/shoptuig-1.png" alt="">
        </div>
        <div class="tips">自定义推广链接   <span style="margin-left: 10px;"></span>   精准分析 <span style="margin-left: 10px;"></span>助力裂变</div>
       
        <el-button type="primary" v-hasPermi="['tuiguang:add']" size="small" @click="openCreate" class="zdy-btn zdy-btn-rent">新建推广
          <img class="lines-img" src="@/assets/img/yunji-jiant.png" alt="">
        </el-button>
      </div>
      <div>
        <img class="titles-right-img" src="@/assets/img/shoptuig.png" alt="">
      </div>
    </div>
    <div class="customTab">
      <el-tabs type="border-card" v-model="activeTab" @tab-click="handleTabChange" v-loading="loading">
        <el-tab-pane label="推广列表" name="promotion">
          <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="80px">
             <el-form-item label="推广名称" prop="inviteCode">
                            <el-select v-model="queryParams.inviteCode" clearable filterable placeholder="请选择推广名称">
                                <el-option v-for="item in promotionOptions" :key="item.inviteCode" :label="item.inviteName" :value="item.inviteCode" 
                                    />
                            </el-select>
                        </el-form-item>

           
            <el-form-item label="负责人" prop="inviteUserId">
              <el-select v-model="queryParams.inviteUserId" clearable filterable placeholder="请选择负责人">
                <el-option v-for="item in employeeOptions" :key="item.userId" :label="item.nickName"
                  :value="item.userId" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" clearable placeholder="请选择状态">
                <el-option label="启用" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item class="btns">
              <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
              <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            
            </el-form-item>
          </el-form>

          <div >
            <el-table :data="tableData.records" border stripe v-loading="loading" :key="'table-1'">
              <el-table-column align="center" prop="inviteName" label="推广名称" min-width="120" />
              <el-table-column align="center" prop="inviteUserName" label="负责人" min-width="120" />
              <!-- <el-table-column align="center" prop="link" label="推广链接" min-width="220" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-button type="text" @click="showQrcode(scope.row)">查看</el-button>
                </template>
              </el-table-column> -->
              <el-table-column align="center" prop="inviteCode" label="推广码" min-width="120">
                  <template slot-scope="scope">
                    <div class="flex" style="cursor: pointer; justify-content: center;align-items: center;" @click="copy(scope.row.inviteCode)">
                      {{ scope.row.inviteCode }}
                     
<i class="el-icon-copy-document" style="color:#6C5DD3;margin-left: 2px;"></i>

                    </div>
                    
                  </template>
                </el-table-column>
              <el-table-column align="center" prop="createTime" label="创建时间" min-width="160" />
             
              <el-table-column align="center" prop="status" label="状态" min-width="100">
                <template slot-scope="scope">
                  <el-switch @change="statusChange(scope.row)"  v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="2"></el-switch>

                  <!-- <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{ scope.row.status == 1 ? '启用' : '停用' }}</el-tag> -->
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" min-width="160">
                <template slot-scope="scope">
                  <el-button type="text" @click="showQrcode(scope.row)">推广链接</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pages-box">
            <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>

          <create-promotion-dialog ref="createDialog" :employeeOptions="employeeOptions" :existingCodes="existingCodes"
            @submit="createPromotion" />
          <link-qrcode-dialog ref="qrcodeDialog" />
        </el-tab-pane>

         <el-tab-pane label="推广明细" name="statistics">
           <el-form :model="statisticsQuery" ref="statisticsForm" :inline="true" class="search-form-new" label-width="80px">
             <el-form-item label="事件" prop="behavior">
               <el-select v-model="statisticsQuery.behavior" clearable placeholder="请选择事件">
                <el-option label="点击" :value="1" />
                <el-option label="下载" :value="2" />
                <el-option label="安装" :value="3" />
                 <el-option label="注册" :value="4" />
                 <el-option label="咨询" :value="5" />
                 <el-option label="支付" :value="6" />
               </el-select>
             </el-form-item>
             <el-form-item label="推广名称" prop="inviteCode">
             <el-select v-model="statisticsQuery.inviteCode" clearable filterable placeholder="请选择推广名称">
                                <el-option v-for="item in promotionOptions" :key="item.inviteCode" :label="item.inviteName" :value="item.inviteCode" 
                                    />
                            </el-select>
             </el-form-item>
             <el-form-item class="btns">
               <el-button type="primary" icon="el-icon-search" @click="searchStatistics">搜索</el-button>
               <el-button type="warning" icon="el-icon-refresh" @click="resetStatisticsQuery">重置</el-button>
             </el-form-item>
           </el-form>

           <div>
             <el-table :data="statisticsData.records" border stripe v-loading="statisticsLoading" :key="'table-2'">
               <el-table-column align="center" prop="inviteName" label="推广名称" min-width="120" />
               <el-table-column align="center" prop="inviteCode" label="推广码" min-width="120" />
               <el-table-column align="center" prop="behavior" label="事件" min-width="100">
                 <template slot-scope="scope">
                  {{ getEventText(scope.row.behavior) }}
                 </template>
               </el-table-column>
                <el-table-column align="center" prop="source" label="渠道" min-width="100">
                 <template slot-scope="scope">
                  {{ getEventsource(scope.row.source) }}
                 </template>
               </el-table-column>
               <el-table-column align="center" prop="userName" label="用户昵称" min-width="120" />
               <el-table-column align="center" prop="userIp" label="用户IP" min-width="120" />
               <el-table-column align="center" prop="createTime" label="时间" min-width="160" />
             </el-table>
           </div>

           <div class="pages-box">
             <pagination v-show="statisticsData.total > 0" :total="statisticsData.total" :page.sync="statisticsQuery.pageNum"
               :limit.sync="statisticsQuery.pageSize" @pagination="getStatisticsList" />
           </div>
         </el-tab-pane>
      </el-tabs>
    </div>

  </div>

</template>

<script>

import {list , detlist , noPage , update} from "@/api/shopTuig/index";
import supplyConfigApi from "@/api/system/supplyConfig";
import CreatePromotionDialog from "./components/CreatePromotionDialog.vue";
import LinkQrcodeDialog from "./components/LinkQrcodeDialog.vue";
import { t } from "@wangeditor/editor";

export default {
  name: "ShopTuig",
  components: { CreatePromotionDialog, LinkQrcodeDialog },
  data() {
    return {
      loading: false,
      queryParams: { inviteCode: '', inviteUserId: '', status: '', pageNum: 1, pageSize: 10 },
      tableData: { records: [], total: 0 },
      employeeOptions: [],
      existingCodes: [],
      activeTab: 'promotion',
      
      // 推广明细相关
      statisticsQuery: { behavior: '', inviteCode: '', pageNum: 1, pageSize: 10 },
      statisticsData: { records: [], total: 0 },
      statisticsLoading: false,
       promotionOptions: [],
    };
  },
   computed: {
      shopInfo() {
      return this.$store.getters.shopInfo;
    },
   },
  
  
  mounted() {
     this.getPromotionOptions();
    this.getEmployees();
    this.getList();
  },
  methods: {
    handleTabChange(e) {
      if (e.name === 'statistics') {
        this.getStatisticsList();
      }else {
        this.getList();

      }
    },
       // 筛选项
        getPromotionOptions() {
            noPage().then(res => {
                this.promotionOptions = res.rows
            })

        },
    // 获取员工
    getEmployees() {
      supplyConfigApi.getAllUserList({ userNewType: 1 }).then(res => {
        this.employeeOptions = res.rows || [];
      });
    },
    // 列表
    getList() {
      this.loading = true;
     list(this.queryParams).then(res=> {
       this.tableData.records =res.rows;
       this.tableData.total = res.total;
        
     }).finally(()=>{
       this.loading = false;
     });
      
    },
    search() { this.queryParams.pageNum = 1; this.getList(); },

    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams.pageNum = 1;
      this.getList();
    },
    openCreate() { this.$refs.createDialog.open(); },
    createPromotion() {
      this.getList();
      this.getPromotionOptions()
    },
    showQrcode(row) {
      if(this.shopInfo.domain) {
         const domain = this.shopInfo.domain.split(',')
        if(domain.length > 0) {
            const link = `http://${domain[0]}?inviteCode=${row.inviteCode}`;
          this.$refs.qrcodeDialog.open(link , row.inviteName);
        }else {
          this.$message.error('暂无推广地址');
        }
      }
    },
  
    // 推广明细相关方法
    getStatisticsList() {
      this.statisticsLoading = true;
      detlist(this.statisticsQuery).then(res=> {
        this.statisticsData.records = res.rows;
         this.statisticsData.total = res.total;
        this.statisticsLoading = false;
       
      })
  
    },
    searchStatistics() {
      this.statisticsQuery.pageNum = 1;
      this.getStatisticsList();
    },
    resetStatisticsQuery() {
      this.$refs.statisticsForm.resetFields();
      this.statisticsQuery.pageNum = 1;
      this.getStatisticsList();
    },
    getEventsource(event) {
        const map = { 1: 'h5', 2: 'app', 3: 'pc'};
      return map[event] || '-';
    },
    getEventText(event) {
      const map = { 1: '点击', 2: '下载', 3: '安装',4:'注册',5:'咨询',6:'支付'};
      return map[event] || '-';
    },
    copy(inviteCode) {
      console.log(inviteCode,'inviteCode')
       this.$copyText(inviteCode).then(() => this.$message.success('已复制到剪贴板'));
    },
    statusChange(row) {
       const originalRenewal = row.status === 2 ? 1 : 2;
      let statues = row.status == 1 ? '开启推广链接' : '关闭推广链接'
      this.$confirm(`确定要${statues}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await update({ id: row.id, status: row.status })
        this.$message.success('操作成功')
        this.getList()
      }).catch(() => {
        row.status = originalRenewal;
      })
    }
  
  }
}
</script>

<style scoped lang="scss">
.customTab .el-tabs--border-card {
  
    box-shadow: none;
    border: none;
}


.box {
  align-items: center;
  border-radius: 4px;
  padding: 10px 60px 20px;
  background: url('../../assets/img/yunji-bg.png') no-repeat;
  background-size: 100% 100%;
  margin-bottom: 10px;

  .flex-l {
    flex: 1;
  }

  .titles {
    color: rgba(51, 51, 51, 1);
    font-size: 18px;
  }

  .tips {
    color: #030C22;
    font-size: 24px;
    text-decoration-line: underline;
    margin: 0px 0 15px;
   
  }
}

.titles-left-img {
  width: 170px;
}

.titles-right-img {
  width: 200px;
}

.zdy-btn-rent {
  width: 120px;
  font-size: 16px;
  height: 40px;
}

.lines-img {
  margin-top: 2px;
  vertical-align: text-top;
  width: 18px;
  margin-left: 2px;
}
</style>